package smdc.web.controller.system;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import smdc.common.annotation.Log;
import smdc.common.config.RuoYiConfig;
import smdc.common.core.controller.BaseController;
import smdc.common.core.domain.AjaxResult;
import smdc.common.core.domain.entity.SysRole;
import smdc.common.core.domain.entity.SysUser;
import smdc.common.core.page.TableDataInfo;
import smdc.common.enums.BusinessType;
import smdc.common.utils.SecurityUtils;
import smdc.common.utils.StringUtils;
import smdc.common.utils.poi.ExcelUtil;
import smdc.system.domain.EasBaseCourse;
import smdc.system.service.IEasBaseCourseService;
import smdc.system.service.ISysUserService;

/**
 * 订单信息Controller
 *
 * @author ruoyi
 * @date 2023-10-18
 */
@RestController
@RequestMapping("/system/course")
public class EasBaseCourseController extends BaseController {

    @Autowired
    private IEasBaseCourseService easBaseCourseService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询订单信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:course:list')")
    @GetMapping("/list")
    public TableDataInfo list(EasBaseCourse easBaseCourse) {
        SysUser queryUser = new SysUser();
        startPage();

        //1、获取当前登录人的角色roleKey 判断是否是 cdgly
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 获取当前的用户
        String loginUser = user.getUserName();
        if (!"admin".equals(loginUser)) {
            List<SysRole> roles = user.getRoles();
            List<String> roleList = new ArrayList<>();
            for (SysRole role : roles) {
                roleList.add(role.getRoleKey());
            }
            //2、如果是cdgly则获取当前用户的部门id
            if (roleList.contains("cdgly")) {
                Long deptId = user.getDeptId();
                queryUser.setDeptId(deptId);
                //3、通过部门id获取部门下所有用户 使用in语句筛选出结果集
                List<SysUser> sysUsers = sysUserService.selectUserList(queryUser);
                List<String> collectUserName = sysUsers.stream().map(SysUser::getUserName).collect(Collectors.toList());
                easBaseCourse.setUserNameList(collectUserName);
            } else {
                // 获取当前的用户
                easBaseCourse.setLoginUser(loginUser);
            }
        }
        List<EasBaseCourse> list = easBaseCourseService.selectEasBaseCourseList(easBaseCourse);
        return getDataTable(list);
    }

    /**
     * 导出订单信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:course:export')")
    @Log(title = "订单信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EasBaseCourse easBaseCourse) {
        SysUser queryUser = new SysUser();
        startPage();

        //1、获取当前登录人的角色roleKey 判断是否是 cdgly
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 获取当前的用户
        String loginUser = user.getUserName();
        if (!"admin".equals(loginUser)) {
            List<SysRole> roles = user.getRoles();
            List<String> roleList = new ArrayList<>();
            for (SysRole role : roles) {
                roleList.add(role.getRoleKey());
            }
            //2、如果是cdgly则获取当前用户的部门id
            if (roleList.contains("cdgly")) {
                Long deptId = user.getDeptId();
                queryUser.setDeptId(deptId);
                //3、通过部门id获取部门下所有用户 使用in语句筛选出结果集
                List<SysUser> sysUsers = sysUserService.selectUserList(queryUser);
                List<String> collectUserName = sysUsers.stream().map(SysUser::getUserName).collect(Collectors.toList());
                easBaseCourse.setUserNameList(collectUserName);
            } else {
                // 获取当前的用户
                easBaseCourse.setLoginUser(loginUser);
            }
        }

        List<EasBaseCourse> list = easBaseCourseService.selectEasBaseCourseList(easBaseCourse);
        ExcelUtil<EasBaseCourse> util = new ExcelUtil<EasBaseCourse>(EasBaseCourse.class);
        util.exportExcel(response, list, "订单信息数据");
    }

    /**
     * 获取订单信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:course:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(easBaseCourseService.selectEasBaseCourseById(id));
    }

    /**
     * 新增订单信息
     */
    @PreAuthorize("@ss.hasPermi('system:course:add')")
    @Log(title = "订单信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EasBaseCourse easBaseCourse) {
        joinUploadPath(easBaseCourse);
        return toAjax(easBaseCourseService.insertEasBaseCourse(easBaseCourse));
    }

    private void joinUploadPath(EasBaseCourse easBaseCourse) {
        // 上传文件路径 http://101.34.62.7/stage-api
        // String filePath = RuoYiConfig.getUploadPath();
        if (StringUtils.isNotBlank(easBaseCourse.getAvatar())) {
            easBaseCourse.setAvatar("http://101.34.62.7/stage-api" + easBaseCourse.getAvatar());
        }
    }

    /**
     * 修改订单信息
     */
    @PreAuthorize("@ss.hasPermi('system:course:edit')")
    @Log(title = "订单信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EasBaseCourse easBaseCourse) {
        // 上传文件路径
        joinUploadPath(easBaseCourse);
        return toAjax(easBaseCourseService.updateEasBaseCourse(easBaseCourse));
    }

    /**
     * 修改订单利率信息
     */
    @PreAuthorize("@ss.hasPermi('system:course:editRate')")
    @Log(title = "订单信息", businessType = BusinessType.UPDATERATE)
    @PutMapping("/rate")
    public AjaxResult editRate(@RequestBody EasBaseCourse easBaseCourse) {
        return toAjax(easBaseCourseService.updateRateEasBaseCourse(easBaseCourse));
    }

    /**
     * 删除订单信息
     */
    @PreAuthorize("@ss.hasPermi('system:course:remove')")
    @Log(title = "订单信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(easBaseCourseService.deleteEasBaseCourseByIds(ids));
    }

    /**
     * 清理服务器中不需要的图片
     *
     */
    // public static void main(String[] args) {
    //
    //     File file = new File("E:\\project\\shangcheng\\data_file");
    //     List<String> list = new ArrayList<>();
    //     findFile(list,file);
    //     list.forEach(System.out::println);
    // }
    /**
     * 获取文件夹下的所有文件的绝对路径
     * 并存储到传入的List集合中
     *
     * @param absolutePaths
     * @param direct
     * @author maorui
     * @date 2023/11/30 15:15
     */
    public static void findFile(List<String> absolutePaths,File direct){
        if (direct.isDirectory()){
            File[] files = direct.listFiles();
            for (File f: files){
                if (f.isFile()){
                    absolutePaths.add(f.getAbsolutePath());
                }
                findFile(absolutePaths,f);
            }
        }
    }

}
